// 任务管理应用
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const taskForm = document.getElementById('addTaskForm');
    const taskList = document.getElementById('taskList');
    const filterButtons = document.querySelectorAll('.filter-btn');
    
    // 当前过滤状态
    let currentFilter = 'all';
    
    // 初始化任务列表
    loadTasks();
    
    // 添加任务表单提交事件
    taskForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const title = document.getElementById('taskTitle').value.trim();
        const description = document.getElementById('taskDescription').value.trim();
        const priority = document.getElementById('taskPriority').value;
        
        if (title) {
            addTask(title, description, priority);
            taskForm.reset();
        }
    });
    
    // 过滤器按钮点击事件
    filterButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 移除所有按钮的active类
            filterButtons.forEach(btn => btn.classList.remove('active'));
            // 为当前按钮添加active类
            this.classList.add('active');
            // 更新当前过滤器
            currentFilter = this.getAttribute('data-filter');
            // 重新渲染任务列表
            renderTasks();
        });
    });
    
    // 添加新任务
    function addTask(title, description, priority) {
        const tasks = getTasks();
        const newTask = {
            id: Date.now(),
            title,
            description,
            priority,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        tasks.push(newTask);
        saveTasks(tasks);
        renderTasks();
    }
    
    // 切换任务完成状态
    function toggleTaskCompletion(id) {
        const tasks = getTasks();
        const taskIndex = tasks.findIndex(task => task.id === id);
        
        if (taskIndex !== -1) {
            tasks[taskIndex].completed = !tasks[taskIndex].completed;
            saveTasks(tasks);
            renderTasks();
        }
    }
    
    // 编辑任务
    function editTask(id) {
        const tasks = getTasks();
        const task = tasks.find(task => task.id === id);
        
        if (task) {
            const newTitle = prompt('编辑任务标题:', task.title);
            if (newTitle !== null) {
                const newDescription = prompt('编辑任务描述:', task.description);
                if (newDescription !== null) {
                    task.title = newTitle.trim();
                    task.description = newDescription.trim();
                    saveTasks(tasks);
                    renderTasks();
                }
            }
        }
    }
    
    // 删除任务
    function deleteTask(id) {
        if (confirm('确定要删除这个任务吗？')) {
            const tasks = getTasks();
            const filteredTasks = tasks.filter(task => task.id !== id);
            saveTasks(filteredTasks);
            renderTasks();
        }
    }
    
    // 从localStorage获取任务
    function getTasks() {
        const tasksJSON = localStorage.getItem('tasks');
        return tasksJSON ? JSON.parse(tasksJSON) : [];
    }
    
    // 保存任务到localStorage
    function saveTasks(tasks) {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
    
    // 加载任务
    function loadTasks() {
        renderTasks();
    }
    
    // 渲染任务列表
    function renderTasks() {
        const tasks = getTasks();
        
        // 根据当前过滤器筛选任务
        let filteredTasks = tasks;
        if (currentFilter === 'active') {
            filteredTasks = tasks.filter(task => !task.completed);
        } else if (currentFilter === 'completed') {
            filteredTasks = tasks.filter(task => task.completed);
        }
        
        // 清空任务列表
        taskList.innerHTML = '';
        
        // 如果没有任务，显示空状态
        if (filteredTasks.length === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'empty-state';
            emptyState.textContent = currentFilter === 'all' 
                ? '还没有任何任务，添加一个吧！' 
                : `没有${currentFilter === 'active' ? '待完成' : '已完成'}的任务`;
            taskList.appendChild(emptyState);
            return;
        }
        
        // 渲染每个任务
        filteredTasks.forEach(task => {
            const taskElement = document.createElement('div');
            taskElement.className = `task-item ${task.priority} ${task.completed ? 'completed' : ''}`;
            
            const formattedDate = new Date(task.createdAt).toLocaleDateString('zh-CN');
            
            taskElement.innerHTML = `
                <div class="task-content">
                    <div class="task-title">${task.title}</div>
                    ${task.description ? `<div class="task-description">${task.description}</div>` : ''}
                    <div class="task-meta">
                        优先级: ${getPriorityText(task.priority)} | 添加于: ${formattedDate}
                    </div>
                </div>
                <div class="task-actions">
                    <button class="btn-complete">${task.completed ? '标记未完成' : '标记完成'}</button>
                    <button class="btn-edit">编辑</button>
                    <button class="btn-delete">删除</button>
                </div>
            `;
            
            // 添加事件监听器
            const completeBtn = taskElement.querySelector('.btn-complete');
            const editBtn = taskElement.querySelector('.btn-edit');
            const deleteBtn = taskElement.querySelector('.btn-delete');
            
            completeBtn.addEventListener('click', () => toggleTaskCompletion(task.id));
            editBtn.addEventListener('click', () => editTask(task.id));
            deleteBtn.addEventListener('click', () => deleteTask(task.id));
            
            taskList.appendChild(taskElement);
        });
    }
    
    // 获取优先级文本
    function getPriorityText(priority) {
        switch(priority) {
            case 'high': return '高';
            case 'medium': return '中';
            case 'low': return '低';
            default: return '中';
        }
    }
});